package com.atwisdom.star.core.dsl.modelClass.template.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.util.UuidTool;
import com.atwisdom.star.common.vo.ModelType;
import com.atwisdom.star.common.vo.PageInfo;
import com.atwisdom.star.core.dao.pojo.modelClass.logic.LogicModel;
import com.atwisdom.star.core.dao.pojo.modelClass.template.TemplateInstance;
import com.atwisdom.star.core.dao.pojo.modelClass.template.TemplateInstanceHistory;
import com.atwisdom.star.core.dao.pojo.modelClass.template.TemplateModel;
import com.atwisdom.star.core.dao.service.modelClass.template.TemplateInstanceHistoryService;
import com.atwisdom.star.core.dao.service.modelClass.template.TemplateInstanceService;
import com.atwisdom.star.core.dao.service.modelClass.template.TemplateModelService;
import com.atwisdom.star.core.dsl.cache.ModelCacheDslService;
import com.atwisdom.star.core.dsl.modelClass.hier.Impl.HierInstanceDslServiceImpl;
import com.atwisdom.star.core.dsl.modelClass.template.TemplateInstanceDslService;
import com.atwisdom.star.core.dsl.modelClass.utils.QueryBuilder;
import com.atwisdom.star.exception.pojo.BusinessException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TemplateInstanceDslServiceImpl implements TemplateInstanceDslService {

    private TemplateModelService templateModelService;
    private TemplateInstanceService templateInstanceService;
    private TemplateInstanceHistoryService templateInstanceHistoryService;

    private HierInstanceDslServiceImpl hierInstanceDslService;

    private QueryBuilder queryBuilder;

    private ModelCacheDslService modelCacheDslService;

    @Autowired
    public void setModelCacheDslService(ModelCacheDslService modelCacheDslService) {
        this.modelCacheDslService = modelCacheDslService;
    }

    @Autowired
    public void setTemplateModelService(TemplateModelService templateModelService) {
        this.templateModelService = templateModelService;
    }

    @Autowired
    public void setTemplateInstanceService(TemplateInstanceService templateInstanceService) {
        this.templateInstanceService = templateInstanceService;
    }

    @Autowired
    public void setTemplateInstanceHistoryService(TemplateInstanceHistoryService templateInstanceHistoryService) {
        this.templateInstanceHistoryService = templateInstanceHistoryService;
    }

    @Autowired
    public void setQueryBuilder(QueryBuilder queryBuilder) {
        this.queryBuilder = queryBuilder;
    }


    /**
     * 查询全部摘要（通用）
     * @return 返回搞要列表
     */
    @Override
    public List<JSONObject> queryAllInfo() {
        try {
            QueryWrapper<TemplateInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published",true);
            queryBuilder.buildInfoSelection(queryWrapper);
            queryBuilder.buildOrderBy(queryWrapper, null, "className,updateTime");
            List<TemplateInstance> list = templateInstanceService.list();
            List<JSONObject> jsonObjectList = new ArrayList<>();
            list.forEach(ins-> jsonObjectList.add(ins.getInfoJsonObject()));
            return jsonObjectList;
        }catch (Exception ex){
            throw new BusinessException("999999", "无条件查询所有模型信息！");
        }
    }

    /**
     * 分页查询全部摘要（通用）
     * @param pageNumber 参数
     * @param pageSize 参数
     * @param orderBy 参数
     * @return 返回全部搞要列表
     */
    @Override
    public PageInfo queryAllInfoByPage(int pageNumber, int pageSize, String orderBy) {
        try {
            Page<TemplateInstance> pageInfo = new Page<>(pageNumber, pageSize);
            QueryWrapper<TemplateInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published",true);
            queryBuilder.buildInfoSelection(queryWrapper);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            return getPageInfoResult(pageInfo, queryWrapper,true);
        }catch (Exception ex){
            throw new BusinessException("999999", "分页无条件查询摘要模型信息！",ex);
        }
    }

    /**
     * 查询全部数据（通用）
     *
     * @return 返回结果
     */
    @Override
    public List<JSONObject> queryAll() {
        try {
            QueryWrapper<TemplateInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published",true);
            queryBuilder.buildOrderBy(queryWrapper,null,"className,updateTime");
            List<TemplateInstance> list = templateInstanceService.list();
            return this.getTemplateInsJsonObjectList(list);
        }catch (Exception ex){
            throw new BusinessException("999999", "无条件查询所有模型信息！");
        }
    }

    /**
     * 分页无条件查询模型信息
     *
     * @param pageNumber 参数
     * @param pageSize 参数
     * @param orderBy 参数
     * @return 返回值
     */
    @Override
    public PageInfo listAllByPage(int pageNumber,int pageSize,String orderBy) {
        try {
            Page<TemplateInstance> pageInfo = new Page<>(pageNumber, pageSize);
            QueryWrapper<TemplateInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("published",true);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            return getPageInfoResult(pageInfo, queryWrapper,false);
        }catch (Exception ex){
            throw new BusinessException("999999", "分页无条件查询模型信息！");
        }
    }

    /**
     * 查询模型
     *
     * @param condition 查询参数
     * @param className 查询参数
     * @param orderBy 排序参数
     * @return 返回值
     */
    @Override
    public List<JSONObject> query(String condition,String className,String orderBy) {
        try{
            if (StringUtils.isBlank(className)) {
                className = queryBuilder.getClassNameBy(condition);
            }
            condition = queryBuilder.transformOperator(condition);
            condition = this.transformConditionForTemplate(condition,className);
            orderBy =   this.transformOrderByForTemplate(condition,className,orderBy);
            QueryWrapper<TemplateInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotBlank(className),"className", className);
            queryWrapper.eq("published", true);
            queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            List<TemplateInstance> list = templateInstanceService.list(queryWrapper);
            return this.getTemplateInsJsonObjectList(list);
        }catch (Exception ex){
            throw new BusinessException("999999", "查询模型失败！",ex);
        }
    }

    /**
     * 按条件分页查询实例摘要
     *
     * @param pageNumber 查询参数
     * @param pageSize 查询参数
     * @param condition 查询参数
     * @param className 查询参数
     * @param orderBy 排序参数
     * @return 返回值
     */
   public PageInfo queryInfoByPage(int pageNumber,int pageSize, String condition,String className,String orderBy){
       try {
           if (StringUtils.isBlank(className)) {
               className = queryBuilder.getClassNameBy(condition);
           }
           Page<TemplateInstance> pageInfo = new Page<>(pageNumber, pageSize);
           condition = queryBuilder.transformOperator(condition);
           condition = this.transformConditionForTemplate(condition,className);
           orderBy =   this.transformOrderByForTemplate(condition,className,orderBy);
           QueryWrapper<TemplateInstance> queryWrapper = new QueryWrapper<>();
           queryWrapper.eq(StringUtils.isNotBlank(className),"className", className);
           queryWrapper.eq("published", true);
           queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
           queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
           return getPageInfoResult(pageInfo, queryWrapper,true);
       }catch (Exception ex){
           throw new BusinessException("999999", "分页无条件查询模型信息！");
       }
    }

    /**
     * 按条件分页查询实例
     *
     * @param pageNumber 查询参数
     * @param pageSize 查询参数
     * @param condition 查询参数
     * @param className 查询参数
     * @param orderBy 排序参数
     * @return 返回值
     */
    public PageInfo queryByPage(int pageNumber,int pageSize, String condition,String className,String orderBy){
        try {
            if (StringUtils.isBlank(className)) {
                className = queryBuilder.getClassNameBy(condition);
            }
            Page<TemplateInstance> pageInfo = new Page<>(pageNumber, pageSize);
            condition = queryBuilder.transformOperator(condition);
            condition = this.transformConditionForTemplate(condition,className);
            orderBy =   this.transformOrderByForTemplate(condition,className,orderBy);
            QueryWrapper<TemplateInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StringUtils.isNotBlank(className),"className", className);
            queryWrapper.eq("published", true);
            queryWrapper.apply(StringUtils.isNotBlank(condition), condition);
            queryBuilder.buildOrderBy(queryWrapper, orderBy, "className,updateTime,id");
            return getPageInfoResult(pageInfo, queryWrapper,false);
        }catch (Exception ex){
            throw new BusinessException("999999", "分页无条件查询模型信息！");
        }
    }

    /**
     * 添加模型
     *
     * @param type 参数
     * @param className 参数
     * @param name 参数
     * @return 返回值
     */
    @Override
    public JSONObject add(String type, String className,String name) {
        if (existModel(type, className)) {
            try {
                TemplateModel templateModel = this.modelCacheDslService.queryModel(ModelType.Template.getCode(), className);
                JSONObject insJsonObject = new JSONObject();
                insJsonObject.put("instanceId", UuidTool.getUUID32());
                insJsonObject.put("type", type);
                insJsonObject.put("name", name);
                insJsonObject.put("className", className);
                insJsonObject.put("published", true);
                insJsonObject.put("version", templateModel.getVersion());
                insJsonObject.put("values", new JSONObject());
                insJsonObject.put("web", new JSONObject());
                insJsonObject.put("others", new JSONObject());
                TemplateInstance instance = new TemplateInstance(templateModel, insJsonObject);
                this.templateInstanceService.save(instance);
                return instance.getInsJsonObject(templateModel);
            } catch (Exception ex) {
                throw new BusinessException("999999", "添加模型失败！", ex);
            }
        } else {
            throw new BusinessException("999999", "模型不存在,创建实例失败！");
        }
    }

    /**
     * 更新模型属性字段
     * 更新，需要同步更新实例，同步更新历史数据
     * 1、className 和 自定字段
     *
     * @param jsonObject 参数
     * @return 返回值
     */
    @Override
    public JSONObject updateById(JSONObject jsonObject) {
        String id = jsonObject.getString("id");
        if(StringUtils.isBlank(id)){
            throw new BusinessException("999999", "更新id为空操作失败！");
        }
        try {
            TemplateInstance sourceInstance = templateInstanceService.getById(id);
            if(sourceInstance==null){
                throw new BusinessException("999999", "要更新实例不存在，操作失败！");
            }

            TemplateModel model = this.modelCacheDslService.queryModel(ModelType.Template.getCode(), sourceInstance.getClassName());
            TemplateInstance templateInstance =new TemplateInstance(model,jsonObject,sourceInstance.getValues());
            templateInstanceService.getBaseMapper().updateById(templateInstance);

            //添加历史
            TemplateInstanceHistory templateInstanceHistory = new TemplateInstanceHistory();
            BeanUtils.copyProperties(templateInstance,templateInstanceHistory);
            templateInstanceHistory.setId(null);
            this.templateInstanceHistoryService.save(templateInstanceHistory);
            return templateInstance.getInsJsonObject(model);
        }catch (Exception ex){
            throw new BusinessException("999999", "更新模型实例失败！");
        }
    }


    public void updateFieldNullById(JSONObject jsonObject){
        String className = jsonObject.getString("className");
        Long id = jsonObject.getLong("id");
        LogicModel logicModel = this.modelCacheDslService.queryModel(ModelType.Logic.getCode(), className);
        JSONObject values = jsonObject.getJSONObject("values");
        JSONObject features = logicModel.fetchFeatures();
        UpdateWrapper<TemplateInstance> updateWrapper = new UpdateWrapper<>();
        // 遍历 JSONObject 对象
        for (String key : features.keySet()) {
            String v = values.getString(key);
            if(StringUtils.isBlank(v)){
                updateWrapper.set(key, null);
            }
        }
        updateWrapper.eq("id",id);
        templateInstanceService.update(updateWrapper);
    }

    /**
     * 更新模型属性字段
     * 更新，需要同步更新实例，同步更新历史数据
     * 1、className 和 自定字段
     *
     * @param jsonObjectList 参数
     * @return 返回值
     */
    @Override
    public List<JSONObject> updateByIds(List<JSONObject> jsonObjectList) {
        List<JSONObject> resultJsonList = new ArrayList<>();
        jsonObjectList.forEach(j->{
            JSONObject jsonObject = this.updateById(j);
            resultJsonList.add(jsonObject);

        });
        return resultJsonList;
    }


    /**
     * 按类型和类名更新模型实例（配置阶段）
     * @param jsonObject 类型
     * @return 返回模型记录
     */
    @Override
    public List<JSONObject> updateClassName(JSONObject jsonObject) {
        String type = jsonObject.getString("type");
        String className = jsonObject.getString("className");
        if (StringUtils.isBlank(type) || StringUtils.isBlank(className)) {
            throw new BusinessException("999999", "更新模型实例：type,className都不能为空！");
        }

        if (!this.existModel(type, className)) {
            throw new BusinessException("999999", "模型不存在，更新模型实例失败！");
        }

        try {
            QueryWrapper<TemplateInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("className", className);
            queryWrapper.eq("type", type);
            queryWrapper.eq("published", true);
            List<TemplateInstance> instances = this.templateInstanceService.list(queryWrapper);
            List<JSONObject> resList = new ArrayList<>();
            instances.forEach(ins->{
                jsonObject.put("id",ins.getId());
                JSONObject upJsonObject = this.updateById(jsonObject);
                resList.add(upJsonObject);
            });
            return resList;
        } catch (Exception ex) {
            throw new BusinessException("999999", "更新模型类型和类名", ex);
        }
    }


    /**
     * 按ids删除模型,同时删除实例在hier中关联和被关联的数据
     * @param ids id列表
     * @return 返回结果
     */
    public boolean deleteByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            throw new BusinessException("999999", "ids列表不能为空，删除模型失败！");
        }
        //删除缓存
        try {
            QueryWrapper<TemplateInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", ids);
            queryWrapper.eq("published", true);
            queryWrapper.eq("b7", false);
            //删除实例
            this.templateInstanceService.realDelete(queryWrapper);
            this.hierInstanceDslService.deleteByContainerIdList(ModelType.Template.getCode(), ids);
            this.hierInstanceDslService.deleteByLinkIdList(ModelType.Template.getCode(), ids);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "按ids删除模型失败！", ex);
        }
    }

    /**
     * 根据className删除实例，同时删除实例在hier中关联和被关联的数据信息
     * 1、删除实例、2、删除历史 3、更新redis
     *
     * @param className 模型类名
     * @return 返回值
     */
    @Override
    public boolean deleteByClassName(String className)  {
        if (StringUtils.isBlank(className)) {
            throw new BusinessException("999999", "模型类名称不能为空,删除模型实例失败！");
        }
        //删除缓存
        try {
            QueryWrapper<TemplateInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("className", className);
            queryWrapper.eq("published", true);
            //删除模型
            this.templateInstanceService.realDelete(queryWrapper);
            this.hierInstanceDslService.deleteByClassName(ModelType.Template.getCode(), className);
            this.hierInstanceDslService.deleteByLinkClassName(ModelType.Template.getCode(), className);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", String.format("删除模型%s失败!", className), ex);
        }
    }

    /**
     * 根据classNames列表批量删除实例数据信息，同时删除实例在hier中关联和被关联的数据信息
     *
     * @param classNames 参数
     * @return 返回值
     */
    @Override
    public boolean deleteByClassNames(List<String> classNames) {
        if (classNames == null || classNames.size() < 1) {
            throw new BusinessException("999999", "模型类名称列表不能为空,删除模型实例失败！");
        }
        try {
            QueryWrapper<TemplateInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("className", classNames);
            queryWrapper.eq("published", true);
            //删除实例
            this.templateInstanceService.realDelete(queryWrapper);
            this.hierInstanceDslService.deleteByClassNameList(ModelType.Template.getCode(), classNames);
            this.hierInstanceDslService.deleteByLinkClassNameList(ModelType.Template.getCode(), classNames);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "模型类名称列表删除模型失败！");
        }
    }

    /**
     * 按Id 废除模型
     * @param ids 参数
     * @return 返回结果
     */
    public boolean repealByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            throw new BusinessException("999999", "ids列表不能为空，废除模型失败！");
        }
        //删除缓存
        try {
            QueryWrapper<TemplateInstance> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", ids);
            queryWrapper.eq("published", true);
            //删除实例
            this.templateInstanceService.remove(queryWrapper);
            return true;
        } catch (Exception ex) {
            throw new BusinessException("999999", "按ids删除模型失败！", ex);
        }

    }

    /**
     * 批量废除
     *
     * @param classNames 参数
     * @return 返回值
     */
    @Override
    public boolean repealByClassNames(List<String> classNames) {
        if (classNames == null || classNames.size() < 1) {
            throw new BusinessException("999999", "模型类名称列表不能为空,删除模型失败！");
        }
        try {
            QueryWrapper<TemplateModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("className", classNames);
            queryWrapper.eq("published", true);
            //删除模型
            this.templateModelService.remove(queryWrapper);
            return true;
        }catch (Exception ex){
            throw new BusinessException("999999", "模型类名称列表删除模型实例失败！");
        }
    }

    /**
     * 获取分页查询
     * @param pageInfo 分页信息
     * @param queryWrapper 查询wrapper
     * @return 返回结果
     */
    private PageInfo getPageInfoResult(Page<TemplateInstance> pageInfo, QueryWrapper<TemplateInstance> queryWrapper,boolean isInfo) {
        Page<TemplateInstance> queryPage = templateInstanceService.page(pageInfo, queryWrapper);
        List<TemplateInstance> records = queryPage.getRecords();
        List<JSONObject> jsonObjectList;
        if(isInfo){
            jsonObjectList = this.getTemplateInsInfoJsonObjectList(records);
        }else{
            jsonObjectList = this.getTemplateInsJsonObjectList(records);
        }
        Page<JSONObject> queryPageDTO = new Page<>();
        BeanUtils.copyProperties(queryPage, queryPageDTO);
        queryPageDTO.setRecords(jsonObjectList);
        return PageInfo.of(queryPageDTO);
    }

    /**
     * 检查模型是否存在
     * @param type 类型
     * @param className 类名称
     * @return 返回是否存，true 存在，false 不存在
     */
    private boolean existModel(String type, String className) {
        QueryWrapper<TemplateModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(type), "type", type);
        queryWrapper.eq(StringUtils.isNotBlank(className), "className", className);
        queryWrapper.eq("published", true);
        long count = this.templateModelService.count(queryWrapper);
        return count > 0;
    }

    /**
     * 将模型实例列表转成JSONObject 列表
     *
     * @param instances 模型实例
     * @return 返回结果
     */
    public List<JSONObject> getTemplateInsInfoJsonObjectList(List<TemplateInstance> instances) {
        List<JSONObject> jsonList = new ArrayList<>();
        instances.forEach(ins -> {
            JSONObject infoJsonObject = ins.getInfoJsonObject();
            jsonList.add(infoJsonObject);

        });
        return jsonList;
    }

    /**
     * 将模型实例列表转成JSONObject 列表
     *
     * @param instances 模型实例
     * @return 返回结果
     */
    public List<JSONObject> getTemplateInsJsonObjectList(List<TemplateInstance> instances) {
        List<TemplateModel> models = this.templateModelService.list();
        List<JSONObject> jsonList = new ArrayList<>();
        instances.forEach(ins -> {
            TemplateModel templateModel = models.stream().filter(m -> m.getClassName().equalsIgnoreCase(ins.getClassName())).findFirst().orElse(null);
            JSONObject insJsonObject = ins.getInsJsonObject(templateModel);
            jsonList.add(insJsonObject);
        });
        return jsonList;
    }

    /**
     * 查询条件字段转换
     *
     * @param condition            参数
     * @param className            参数
     */
    public String transformConditionForTemplate(String condition, String className) {
        if (StringUtils.isBlank(condition)) {
            return "";
        }
        if (StringUtils.isBlank(className)) {
            className = queryBuilder.getClassNameBy(condition);
        }
        if (StringUtils.isBlank(className)) {
            return condition;
        }
        if (StringUtils.isNotBlank(className) && StringUtils.isNotBlank(condition)) {
            TemplateModel templateModel = modelCacheDslService.queryModel(ModelType.Template.getCode(), className);
            if (templateModel != null) {
                List<JSONObject> featureProperties = templateModel.fetchFeatureProperties();
                for (JSONObject item : featureProperties) {
                    String name = item.getString("name");
                    String code = item.getString("code");
                    // condition = condition.replaceAll(name, code);
                    condition = condition.replaceAll("(?<!['%a-z0-9_\\u4e00-\\u9fa5])"+name, code);
                }
                List<JSONObject> featureNoProperties = templateModel.fetchNonFeaturesProperties();
                for (JSONObject item : featureNoProperties) {
                    String name = item.getString("name");
                    condition = condition.replaceAll("(?<!['%a-z0-9_\\u4e00-\\u9fa5])"+name,
                            java.util.regex.Matcher.quoteReplacement("JSON_EXTRACT(insValues,'$.")+name+
                                    "')");
                }
            }
        }
        return condition;
    }

    /**
     * 查询条件字段转换
     *
     * @param condition 取className 条件
     * @param className 类名
     * @param orderBy   排序参数
     */
    public String transformOrderByForTemplate(String condition, String className, String orderBy) {
        if (StringUtils.isBlank(orderBy)) {
            return "";
        }
        if (StringUtils.isBlank(className)) {
            className = queryBuilder.getClassNameBy(condition);
        }

        if (StringUtils.isBlank(className)) {
            return orderBy;
        }
        orderBy = orderBy.replaceAll(" ", "");
        TemplateModel templateModel = modelCacheDslService.queryModel("template", className);
        List<JSONObject> featureProperties = templateModel.fetchFeatureProperties();
        for (JSONObject item : featureProperties) {
            String name = item.getString("name");
            String code = item.getString("code");
            orderBy = orderBy.replaceAll(name, code);
        }
        return orderBy;
    }



}
